package cn.hfjava.kz.listener;

import cn.hfjava.kz.entity.excel.StudentExcel;
import cn.hfjava.kz.service.StudentService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;

import java.util.ArrayList;
import java.util.List;

public class StudentListener implements ReadListener<StudentExcel> {
    private static final int BATCH_COUNT = 10000;
    private StudentService studentService;
    private List<StudentExcel> list = new ArrayList<>(BATCH_COUNT);
    private String createdBy;
    private Integer userId;
    private boolean checkDuplicates;
    private List<String> errorMessages = new ArrayList<>(); // 用于存储错误信息

    public StudentListener(StudentService studentService, String createdBy, Integer userId, boolean checkDuplicates) {
        this.studentService = studentService;
        this.createdBy = createdBy;
        this.userId = userId;
        this.checkDuplicates = checkDuplicates;
    }

    @Override
    public void invoke(StudentExcel studentExcel, AnalysisContext analysisContext) {
        System.out.println("正在处理学生信息: " + studentExcel);
        list.add(studentExcel);
        if (list.size() >= BATCH_COUNT) {
            processBatch();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (list.size() > 0) {
            processBatch();
        }
    }

    private void processBatch() {
        if (checkDuplicates) {
            // 检测重复数据
            boolean hasDuplicates = studentService.checkForDuplicates(list);
            if (hasDuplicates) {
                errorMessages.add("重复数据"); // 收集错误信息
            } else {
                studentService.addData(list, createdBy, userId);
            }
        } else {
            // 保存数据
            studentService.addData(list, createdBy, userId);
        }
        list.clear();
    }

    public List<String> getErrorMessages() {
        return errorMessages;
    }
}
